import {
    IdlePriority,
    ImmediatePriority,
    LowPriority,
    NormalPriority,
    UserBlockingPriority
} from "scheduler/src/SchedulerPriorities";
import {peek, pop, push} from "scheduler/src/forks/SchedulerMinHeap";

let startTime=-1
//过期时间
var maxSigned31BitInt = 1073741823;
// Times out immediately
var IMMEDIATE_PRIORITY_TIMEOUT = -1;
// Eventually times out
var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
var NORMAL_PRIORITY_TIMEOUT = 5000;
var LOW_PRIORITY_TIMEOUT = 10000;
// Never times out
var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt;
var taskIdCounter = 1;
const heapQueue=[]
let scheduleHostCallBack=null
const TaskRunEvent = 5;

let message=new MessageChannel()
let port1=message.port1
let port2=message.port2
port1.onmessage=PreformWorkUntilDeadline




/***
 * 获取浏览器运行时间
 * @returns {DOMHighResTimeStamp}
 */
function getCurrentTime(){
    return performance.now()
}


export function shouldYieldToHost(){
  return getCurrentTime()-startTime > TaskRunEvent
}


/***
 * 开始当前任务的时间
 * @param currentTime
 */
function workLoop(currentTime){
    let firstTask=peek(heapQueue)
    while (firstTask){
       if(firstTask.expirationTime > currentTime && shouldYieldToHost()){
           break
       }
      if(typeof firstTask.callBack === 'function'){
          let nextCallBack=firstTask.callBack(firstTask.expirationTime)
          firstTask.callBack=nextCallBack
      }else{
          pop(heapQueue)
          firstTask=peek(heapQueue)
      }
    }
    if(firstTask){
        return true
    }else{
        return false
    }
}

export function scheduleCallBack(priorityLevel,callBack){
    let startTime=getCurrentTime()
    let timeout;
    //设置过期时间
    switch (priorityLevel) {
        case ImmediatePriority:
            timeout = IMMEDIATE_PRIORITY_TIMEOUT;
            break;
        case UserBlockingPriority:
            timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
            break;
        case IdlePriority:
            timeout = IDLE_PRIORITY_TIMEOUT;
            break;
        case LowPriority:
            timeout = LOW_PRIORITY_TIMEOUT;
            break;
        case NormalPriority:
        default:
            timeout = NORMAL_PRIORITY_TIMEOUT;
            break;
    }
    let expirationTime=startTime+timeout
    //创建一个任务
    let task={
        id:taskIdCounter++,
        callBack,
        startTime,
        expirationTime,
        sortIndex:expirationTime
    }
    push(heapQueue,task)
    requestHostCallback(workLoop)
}


function schedulePreformWorkUntilDeadline(){
    port2.postMessage(null)
}

//这里只有五毫秒时间执行
function PreformWorkUntilDeadline(){
   let currentTime=startTime=getCurrentTime()
    debugger
   let nextTask=scheduleHostCallBack && scheduleHostCallBack(currentTime)
   if(nextTask){
       schedulePreformWorkUntilDeadline()
   }else{
       scheduleHostCallBack=null
   }

}

//绑定给全局callback
function requestHostCallback(workLoop){
    scheduleHostCallBack=workLoop
    schedulePreformWorkUntilDeadline()
}